#include "sFlashLoad.h"

extern FATFS fs;
extern FIL FwFile;
extern unsigned int br;

u32 binReadBuff[512];

void binUpdate(void)
{
	int fwFileSize;
	int fwPageSize;
	unsigned int i,j;
	
	fwFileSize = f_size(&FwFile);
	printf("\r\nFile Size : %.2fKB",(float)fwFileSize/1024);
	
	//get number of page to write
	fwPageSize = fwFileSize/2048;
	if(fwFileSize%2048)
		fwPageSize++;
	printf("\r\nNumber Of Page to Write : %d",fwPageSize);
	
	//start writing
	printf("\r\nStart Writing ... \n\r");
	//RCC_HSICmd(ENABLE);
	FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_EOP|FLASH_FLAG_PGERR|FLASH_FLAG_WRPRTERR);
	//printf("\r\n%x %x %x %x",binReadBuff[0],binReadBuff[1],binReadBuff[2],binReadBuff[3]);
	//printf("\r\n%x %x %x %x",binReadBuff[2044],binReadBuff[2045],binReadBuff[2046],binReadBuff[2047]);
	for(i=0 ; i<fwPageSize ; i++)
	{
		printf("\r\nPage %d at 0x%7x",i,ApplicationAddress + i*2048);
		f_read(&FwFile,binReadBuff,2048,&br);
		FLASH_ErasePage(ApplicationAddress + i*2048);
		for(j=0 ; j<512 ; j++)
		{
			FLASH_ProgramWord(ApplicationAddress + i*2048 + j*4 , binReadBuff[j]);
			//printf("%x",binReadBuff[j]);
		}
	}
	FLASH_Lock();
	printf("\r\nFinish Writing !!\r\n");
	//printf("\r\n %x",(*(__IO uint32_t*)ApplicationAddress));
	return;
}

